package com.alipay.app.groupmeal.standard.ui.b.function;

import static android.content.Context.MODE_PRIVATE;
import static android.view.View.VISIBLE;
import static com.alipay.app.groupmeal.standard.constant.ConfigConstant.onOffLine;

import android.content.Context;
import android.content.SharedPreferences;
import android.view.Display;
import android.view.KeyEvent;

import com.alipay.app.groupmeal.standard.R;
import com.alipay.app.groupmeal.standard.base.BasePresentation;
import com.alipay.app.groupmeal.standard.bean.TitleBean;
import com.alipay.app.groupmeal.standard.constant.BaseConstant;
import com.alipay.app.groupmeal.standard.constant.ConfigConstant;
import com.alipay.app.groupmeal.standard.constant.SystemConsts;
import com.alipay.app.groupmeal.standard.event.EventManager;
import com.alipay.app.groupmeal.standard.ui.b.function.amount.BScreenAmount;
import com.alipay.app.groupmeal.standard.ui.b.function.mode.BScreenCensus;
import com.alipay.app.groupmeal.standard.ui.b.function.mode.BScreenDeviceInfo;
import com.alipay.app.groupmeal.standard.ui.b.function.mode.BScreenDownFk;
import com.alipay.app.groupmeal.standard.ui.b.function.mode.BScreenModeSelect;
import com.alipay.app.groupmeal.standard.ui.b.function.mode.BScreenSerialPort;
import com.alipay.app.groupmeal.standard.ui.b.function.mode.BScreenSetExpireTimeDialog;
import com.alipay.app.groupmeal.standard.ui.b.function.mode.BScreenSetSuccessTimeDialog;
import com.alipay.app.groupmeal.standard.ui.c.abcp.CHexiaoAuthActivity;
import com.alipay.app.groupmeal.standard.ui.b.util.DeviceInfoManager;
import com.alipay.app.groupmeal.standard.widget.business.FakeToastView;
import com.alipay.app.groupmeal.standard.widget.business.StatusBar;
import com.alipay.sdk.util.LogUtil;
import com.gzdh.eventbut.DownFkEvent;
import com.gzdh.eventbut.InitDeviceEvent;
import com.gzdh.eventbut.UnBindEvent;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

/**
 * @ProjectName: 团餐
 * @ClassName: FunctionPre
 * @Description: 功能列表
 * @Author: bd-001935
 * @CreateDate: 4/15/22 8:31 PM
 * @UpdateUser: bd-001935
 * @UpdateDate: 4/15/22 8:31 PM
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
public class FunctionPre extends BasePresentation {


    private int menuType = 0;

    private Context mContext;

    //功能列表
    private BScreenMenuList mFunctionsView;

    //固定金额&自由金额
    private BScreenAmount mScreenAmount;

    private FakeToastView mToastViewAmount;

    //收银模式
    private BScreenModeSelect mModeSelect;

    //串口通讯设备选择
    private BScreenSerialPort mSerialPort;

    private StatusBar mStatusBar;

    //订单列表
    private BScreenOrderList mOrderListView;

    //下载FK
    private BScreenDownFk mDownFk;

    //设备信息
    private BScreenDeviceInfo mDeviceInfo;

    //交易统计页面
    private BScreenCensus mScreenCensus;
    private boolean upDateOnOffline = false;


    private BScreenSetSuccessTimeDialog bScreenSetSuccessTimeDialog;

    private BScreenSetExpireTimeDialog bScreenSetExpireTimeDialog;

    public FunctionPre(Context outerContext, Display display) {
        super(outerContext, display);
        mContext = outerContext;
    }

    @Override
    protected int getLayoutId() {

        return R.layout.view_presentation3;


    }

    @Override
    protected void initView() {
        mFunctionsView = findViewById(R.id.functionsView);
        mDownFk = findViewById(R.id.downFk);
        mScreenCensus = findViewById(R.id.census);
        mStatusBar = findViewById(R.id.statusBar);
        mModeSelect = findViewById(R.id.modeSelect);
        mSerialPort = findViewById(R.id.serialPort);
        mScreenAmount = findViewById(R.id.amount);
        mOrderListView = findViewById(R.id.orderListView);
        mDeviceInfo = findViewById(R.id.deviceInfo);
        mToastViewAmount = findViewById(R.id.toastViewAmount);
        bScreenSetSuccessTimeDialog = findViewById(R.id.dialog_set_success_time);
        bScreenSetExpireTimeDialog = findViewById(R.id.dialog_set_expire_time);
    }

    @Override
    protected void initData() {

        //功能列表
        showMenuList();

        /**
         * 收银模式 监听器
         */
        mModeSelect.setOnModeSelectListener(new BScreenModeSelect.OnModeSelectListener() {
            @Override
            public void onChange() {
                mScreenAmount.changeSecret();
            }

            @Override
            public void onBackKey() {
                mFunctionsView.request();
            }
        });

        mSerialPort.setOnModeSelectListener(new BScreenSerialPort.OnModeSelectListener() {
            @Override
            public void onChange() {
                mScreenAmount.changeSecret();
            }

            @Override
            public void onBackKey() {
                mFunctionsView.request();
            }
        });

        /**
         * 固定金额&自由金额 监听器
         */
        mScreenAmount.setAmountKeyEventListener(new BScreenAmount.AmountKeyEventListener() {
            @Override
            public void onEnterKey(String amount, boolean isFree) {
                //在交易时回车按钮触发
                if (functionPreListener != null) {
                    functionPreListener.awaitPay(amount, isFree, false);
                }
            }

            @Override
            public void onDownKey(boolean isFree) {
            }

            @Override
            public void onFunctionKey() {
                mFunctionsView.clearFocusView();
            }
        });

        /**
         * 入场核销监听器
         */
        mScreenAmount.setHexiaoEventListener(() -> {

            CHexiaoAuthActivity.startActAbcp(mContext);
        });

        if (DeviceInfoManager.isAutoDownFk()) {
            showDownFk();
        } else {
            setBScreenMode();
        }

        bScreenSetSuccessTimeDialog.setSetting(true);
        bScreenSetSuccessTimeDialog.setAmountConfirmListener(new BScreenSetSuccessTimeDialog.AmountConfirmListener() {
            @Override
            public void onConfirm(String amount) {
                ConfigConstant.successTime = Integer.parseInt(amount);
                SharedPreferences sysInfo = mContext.getSharedPreferences("sysCost", MODE_PRIVATE);
                SharedPreferences.Editor editor = sysInfo.edit();
                editor.putInt("successTime", ConfigConstant.successTime);
                editor.commit();
                bScreenSetSuccessTimeDialog.dismiss();
            }
        });

        bScreenSetExpireTimeDialog.setSetting(true);
        bScreenSetExpireTimeDialog.setAmountConfirmListener(new BScreenSetExpireTimeDialog.AmountConfirmListener() {
            @Override
            public void onConfirm(String amount) {
                ConfigConstant.expireTime = Integer.parseInt(amount);
                SharedPreferences sysInfo = mContext.getSharedPreferences("sysCost", MODE_PRIVATE);
                SharedPreferences.Editor editor = sysInfo.edit();
                editor.putInt("expireTime", ConfigConstant.expireTime);
                editor.commit();
                bScreenSetExpireTimeDialog.dismiss();
            }
        });
    }


    /**
     * 功能菜单初始化
     */
    private void showMenuList() {
        menuType = 0;
        mFunctionsView.setTitleText(getContext().getString(R.string.function));
        mFunctionsView.setList(getFunctionsTitle());
        mFunctionsView.setOnMyItemClickListener((adapter, view, position) -> {
            TitleBean bean = (TitleBean) adapter.getItem(position);
            if (bean.type == BaseConstant.FUNCTION_TYPE.CASHIER_MODE)
                showModeSelect();
            else if (bean.type == BaseConstant.FUNCTION_TYPE.SERIAL_PORT)
                showSerialPort();
            else if (bean.type == BaseConstant.FUNCTION_TYPE.ORDERS)
                showFindOrdersList();
            else if (bean.type == BaseConstant.FUNCTION_TYPE.OFFLINE)
                showOfflineList();
            else if (bean.type == BaseConstant.FUNCTION_TYPE.SETTING)
                showSettingList();
            else if (bean.type == BaseConstant.FUNCTION_TYPE.CENSUS)
                showCensus();
            else if (bean.type == BaseConstant.FUNCTION_TYPE.D_EXPIRE_TIME) {
                bScreenSetExpireTimeDialog.setVisibility(VISIBLE);
                bScreenSetExpireTimeDialog.getTv_amount().setText(String.valueOf(ConfigConstant.expireTime));
            }
        });
        mFunctionsView.clearFocusView();
    }

    /**
     * 脱机交易初始化
     */
    private void showOfflineList() {
        menuType = 1;
        mFunctionsView.setTitleText(getContext().getString(R.string.offline_deal));
        mFunctionsView.setList(getOfflineTitle());
        mFunctionsView.setOnMyItemClickListener((adapter, view, position) -> {
            TitleBean bean = (TitleBean) adapter.getItem(position);
            if (bean.type == BaseConstant.PAY_TYPE.ONLINE) {
                closeFunction();
                //开始脱机交易
                onOffLine = onOffLine ? false : true;
                showOfflineList();
            } else if (bean.type == BaseConstant.PAY_TYPE.ONLINE_REPORT) {
                showNoHavePostOrders();
            } else if (bean.type == BaseConstant.PAY_TYPE.TONG_BU_ORDER) {
//                mToastViewAmount.showToastAndInterval("正在同步");
                closeFunction();
                upDateOnOffline = true;
                EventBus.getDefault().post(new EventManager.tongbuOrder());
                showOfflineList();
            }
        });
        mFunctionsView.clearFocusView();
    }

    /**
     * 订单查询
     */
    private void showFindOrdersList() {
        menuType = 3;
        mFunctionsView.setTitleText(getContext().getString(R.string.find_order));
        mFunctionsView.setList(findOrdersList());
        mFunctionsView.setOnMyItemClickListener((adapter, view, position) -> {
            TitleBean bean = (TitleBean) adapter.getItem(position);
            if (bean.type == BaseConstant.ORDER.USER_ORDER) {
                if (userOrderListener != null) {
                    userOrderListener.userEnter();
                }
                showMenuList();
                mFunctionsView.dismiss();
                setBScreenMode();
            } else if (bean.type == BaseConstant.ORDER.SYS_ORDER) {
                showOrders();
            }
        });
        mFunctionsView.clearFocusView();
    }

    /**
     * 设置页面初始化
     */
    private void showSettingList() {
        menuType = 2;
        mFunctionsView.setTitleText(getContext().getString(R.string.setting));
        mFunctionsView.setList(getSettingTitle());
        mFunctionsView.setOnMyItemClickListener((adapter, view, position) -> {
            TitleBean bean = (TitleBean) adapter.getItem(position);
            if (bean.type == BaseConstant.SETTING.DOWN_FK)
                showDownFk();
            else if (bean.type == BaseConstant.SETTING.DEVICE_INFO)
                shoDeviceInfo();
            else if (bean.type == BaseConstant.SETTING.AUTO_DOWN_FK) {
                closeFunction();
                DeviceInfoManager.swAutoDownFk();
                showSettingList();
            } else if (bean.type == BaseConstant.SETTING.D_SUCCESS_TIME) {
                //成功倒计时
                bScreenSetSuccessTimeDialog.setVisibility(VISIBLE);
                bScreenSetSuccessTimeDialog.getTv_amount().setText(String.valueOf(ConfigConstant.successTime));

            }
        });
        mFunctionsView.clearFocusView();

    }

    /**
     * 显示订单查看
     */
    private void showOrders() {
        mOrderListView.setList();
        mFunctionsView.dismiss();
    }

    /**
     * 显示脱机订单查看
     */
    private void showNoHavePostOrders() {
        mOrderListView.setNoHavePostList();
        mFunctionsView.dismiss();
    }

    /**
     * 取消按键触发
     *
     * @param event
     * @return
     */
    @Override
    public boolean onKeyEventBack(KeyEvent event) {
        upDateOnOffline = false;
        if (bScreenSetSuccessTimeDialog != null && bScreenSetSuccessTimeDialog.isVisibility()) {
            bScreenSetSuccessTimeDialog.dismiss();
            return false;
        }
        if (bScreenSetExpireTimeDialog != null && bScreenSetExpireTimeDialog.isVisibility()) {
            bScreenSetExpireTimeDialog.dismiss();
            return false;
        }
        if (mModeSelect != null && mModeSelect.isVisibility()) {
            return mModeSelect.dispatchKeyEvent(event);
        }
        if(mSerialPort != null && mSerialPort.isVisibility()) {
            return mSerialPort.dispatchKeyEvent(event);
        }
        if (mDownFk != null && mDownFk.isVisibility()) {
            mDownFk.dismiss();
            mFunctionsView.request();
            return false;
        }
        if (mScreenCensus != null && mScreenCensus.isVisibility()) {
            mScreenCensus.dismiss();
            mFunctionsView.request();
            return false;
        }
        if (mDeviceInfo != null && mDeviceInfo.isVisibility()) {
            mDeviceInfo.dismiss();
            mFunctionsView.request();
            return false;
        }
        if (mOrderListView != null && mOrderListView.isVisibility()) {
            mOrderListView.dismiss();
            mFunctionsView.request();
            return false;
        }
        if (mFunctionsView != null && mFunctionsView.isVisibility()) {
            closeFunction();
            return false;
        }
        if (mScreenAmount != null && mScreenAmount.isVisibility()) {
            if (mScreenAmount.getAwait_pay() != null
                    && mScreenAmount.getAwait_pay().isVisibility()) {
                return mScreenAmount.dispatchKeyEvent(event);
            } else if (mScreenAmount.getHexiaoAmount() != null
                    && mScreenAmount.getHexiaoAmount().isVisibility()) {
                return mScreenAmount.dispatchKeyEvent(event);
            }
//            ActivityUtils.finishAllActivities();
            mScreenAmount.clearAmount();
            return false;
        }
        return super.onKeyEventBack(event);
    }

    /**
     * 数字按钮触发
     *
     * @param event
     * @return
     */
    @Override
    public boolean onKeyEventNum(KeyEvent event) {
        //固定金额&自由金额
        if (mScreenAmount != null && mScreenAmount.isVisibility()) {
            return mScreenAmount.dispatchKeyEvent(event);
        }
        if (bScreenSetSuccessTimeDialog != null && bScreenSetSuccessTimeDialog.isVisibility()) {
            return bScreenSetSuccessTimeDialog.dispatchKeyEvent(event);
        }
        if (bScreenSetExpireTimeDialog != null && bScreenSetExpireTimeDialog.isVisibility()) {
            return bScreenSetExpireTimeDialog.dispatchKeyEvent(event);
        }
//        if (mModeSelect != null && mModeSelect.isVisibility()) {
//            return mModeSelect.dispatchKeyEvent(event);
//        }
        return super.onKeyEventNum(event);
    }

    /**
     * 回车按键触发
     *
     * @param event
     * @return
     */
    @Override
    public boolean onKeyEventEnter(KeyEvent event) {
        //固定金额&自由金额
        if (mScreenAmount != null && mScreenAmount.isVisibility()) {
            return mScreenAmount.dispatchKeyEvent(event);
        }
        //收银模式
        if (mModeSelect != null && mModeSelect.isVisibility()) {
            return mModeSelect.dispatchKeyEvent(event);
        }
        if(mSerialPort != null && mSerialPort.isVisibility()) {
            return mSerialPort.dispatchKeyEvent(event);
        }
        //核销模式

        if (bScreenSetSuccessTimeDialog != null && bScreenSetSuccessTimeDialog.isVisibility()) {
            return bScreenSetSuccessTimeDialog.onKeyEventEnter(event);
        }
        if (bScreenSetExpireTimeDialog != null && bScreenSetExpireTimeDialog.isVisibility()) {
            return bScreenSetExpireTimeDialog.onKeyEventEnter(event);
        }
        return super.onKeyEventEnter(event);
    }

    /**
     * 上下按键触发
     *
     * @param event
     * @return
     */
    @Override
    public boolean onKeyEventUpAndDown(KeyEvent event) {
        //固定金额&自由金额
        if (mScreenAmount != null && mScreenAmount.isVisibility()) {
            return mScreenAmount.dispatchKeyEvent(event);
        }
        return super.onKeyEventUpAndDown(event);
    }

    /**
     * 功能按键触发
     *
     * @param event
     * @return
     */
    @Override
    public boolean onKeyEventFunction(KeyEvent event) {
        if (mScreenAmount != null && mScreenAmount.isVisibility()) {
            return mScreenAmount.dispatchKeyEvent(event);
        }
        return super.onKeyEventFunction(event);
    }

    /**
     * 获取功能菜单
     *
     * @return
     */
    private List<TitleBean> getFunctionsTitle() {
        List<TitleBean> data = new ArrayList<>();
        data.add(new TitleBean("收银模式", BaseConstant.FUNCTION_TYPE.CASHIER_MODE));
        data.add(new TitleBean("脱机交易", BaseConstant.FUNCTION_TYPE.OFFLINE));
        data.add(new TitleBean("交易统计", BaseConstant.FUNCTION_TYPE.CENSUS));
        data.add(new TitleBean("交易查询", BaseConstant.FUNCTION_TYPE.ORDERS));
        data.add(new TitleBean("更多设置", BaseConstant.FUNCTION_TYPE.SETTING));
        data.add(new TitleBean("等待支付倒计时", BaseConstant.FUNCTION_TYPE.D_EXPIRE_TIME));
        data.add(new TitleBean("串口通讯设备", BaseConstant.FUNCTION_TYPE.SERIAL_PORT));
        return data;
    }

    /**
     * 获取脱机交易菜单
     *
     * @return
     */
    private List<TitleBean> getOfflineTitle() {
        List<TitleBean> data = new ArrayList<>();
        data.add(new TitleBean(onOffLine ? "开启脱机交易" : "关闭脱机交易", BaseConstant.PAY_TYPE.ONLINE));
        data.add(new TitleBean("脱机交易记录", BaseConstant.PAY_TYPE.ONLINE_REPORT));
        data.add(new TitleBean(upDateOnOffline ? "已发起同步" : "同步脱机交易", BaseConstant.PAY_TYPE.TONG_BU_ORDER));
        return data;
    }


    private List<TitleBean> findOrdersList() {
        List<TitleBean> data = new ArrayList<>();
        data.add(new TitleBean("设备交易", BaseConstant.ORDER.SYS_ORDER));
//        data.add(new TitleBean("个人交易", BaseConstant.ORDER.USER_ORDER));
        return data;
    }

    /**
     * 获取设置菜单
     *
     * @return
     */
    private List<TitleBean> getSettingTitle() {
        List<TitleBean> data = new ArrayList<>();
//        data.add(new TitleBean("音量设置", BaseConstant.FUNCTION_TYPE.CASHIER_MODE));
        data.add(new TitleBean("同步白名单", BaseConstant.SETTING.DOWN_FK));
        data.add(new TitleBean("设备信息", BaseConstant.SETTING.DEVICE_INFO));
        data.add(new TitleBean(DeviceInfoManager.isAutoDownFk() ? "已启动自动下载" : "已关闭自动下载", BaseConstant.SETTING.AUTO_DOWN_FK));
        data.add(new TitleBean("成功倒计时", BaseConstant.SETTING.D_SUCCESS_TIME));

        return data;
    }

    /**
     * 收银模式选择
     */
    private void showModeSelect() {
        mModeSelect.setData(getDisplay(), mStatusBar.getHeight());
        mFunctionsView.dismiss();
    }

    /**
     * 串口通讯设备选择
     */
    private void showSerialPort() {
        mSerialPort.setData(getDisplay(), mStatusBar.getHeight(), mContext);
        mFunctionsView.dismiss();
    }

    /**
     * 下载白名单选择
     */
    private void showDownFk() {
        mDownFk.setData(getDisplay(), mStatusBar.getHeight(), getContext());
        mFunctionsView.dismiss();
    }

    /**
     * 设备信息查看选择a
     */
    private void shoDeviceInfo() {
        mDeviceInfo.setData(getDisplay(), mStatusBar.getHeight());
        mFunctionsView.dismiss();
    }

    private void showCensus() {
        mScreenCensus.setData(getDisplay(), mStatusBar.getHeight());
        mFunctionsView.dismiss();
    }


    /**
     * 固定金额
     */
    public void showFixedAmount() {
        mScreenAmount.showFixedAmount();
    }

    /**
     * 自由金额
     */
    public void showInputAmount() {
        mScreenAmount.showInputAmount();
    }

    public void showHexiaoAmount() {
        mScreenAmount.showHexiaoAmount();
    }


    /**
     * 关闭功能列表,返回金额页
     */
    private void closeFunction() {
        switch (menuType) {
            case 1:
            case 2:
            case 3:
                showMenuList();
                return;
        }
        mScreenAmount.setVisibility(VISIBLE);
        mFunctionsView.dismiss();
        setBScreenMode();
    }

    private void setBScreenMode() {
        LogUtil.d("收银模式: ", DeviceInfoManager.getCashierMode());
        if (BaseConstant.CASHIER_MODE.MODE_FREE.equals(DeviceInfoManager.getCashierMode())) {
            //自由金额模式
            showInputAmount();
        }
        if (BaseConstant.CASHIER_MODE.MODE_FIXED.equals(DeviceInfoManager.getCashierMode())) {
            //固定金额模式
            showFixedAmount();
        }
        if (BaseConstant.CASHIER_MODE.MODE_HEXIAO.equals(DeviceInfoManager.getCashierMode())) {
            showHexiaoAmount();
        }
    }

    private FunctionPreListener functionPreListener;

    public void setFunctionPreListener(FunctionPreListener listener) {
        functionPreListener = listener;
    }

    public interface FunctionPreListener {
        void awaitPay(String amount, boolean isFree, boolean isCard);
    }


    private UserOrderListener userOrderListener;

    public void setUserOrderListener(UserOrderListener listener) {
        userOrderListener = listener;
    }

    public interface UserOrderListener {
        void userEnter();
    }

    public void setClearAmount(boolean clearAmount) {
        if (mScreenAmount != null)
            mScreenAmount.setClearAmount(clearAmount);
    }

    public void clearAmount() {
        mScreenAmount.clearAmount();
    }


    @Override
    public void onEvent(Object message) {
        super.onEvent(message);
        if (message instanceof EventManager.clearAmount) {
            LogUtil.d("FunctionPre", "clearAmount");
            clearAmount();
        } else if (message instanceof DownFkEvent) {
            System.out.println("下载白名单消息总线");
            mScreenAmount.dismiss();
            showDownFk();
        } else if
        (message instanceof InitDeviceEvent) {
            System.out.println("初始化设备");
            if (initDevice != null) {
                initDevice.initDeviceListener(0);
            }
        } else if (message instanceof UnBindEvent) {

            if (initDevice != null) {
                initDevice.initDeviceListener(1);
            }
        }
    }


    /**
     * 接收到刷卡回调
     *
     * @param tag 卡片id
     */
    public void onReceiveNfcTag(String tag) {
        SystemConsts.getSystemConsts().setCardSn(tag);  //设置全部刷卡支付
        if (mScreenAmount.getAwait_pay().isVisibility()) {
            LogUtil.d("正在支付中");
            if (functionPreListener != null) {
                LogUtil.d("开始刷卡正在支付中");
                functionPreListener.awaitPay(mScreenAmount.getAwait_pay().getAmount(), false, true);
            }
        }
    }

    public interface InitDevice {
        void initDeviceListener(int type);
    }

    private InitDevice initDevice;

    public void setInitDevice(InitDevice initDevice) {
        this.initDevice = initDevice;
    }
}